package com.wx.task;

import cn.hutool.core.util.RandomUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 线程历史2
 * 阻塞队列 + AtomicBoolean
 *
 * @author wang.xun
 * @date 2023/07/24
 */
@Slf4j
public class ThreadHistory2 implements Runnable{
    // 阻塞队列
    private LinkedBlockingDeque deque = new LinkedBlockingDeque();
    // 知否停止执行
    private AtomicBoolean running = new AtomicBoolean(true);
    @SneakyThrows
    @Override
    public void run() {

        while (running.get()) {
            Object take = deque.take();
            doSomeThing(take);
        }
        log.info("{}停止",Thread.currentThread().getName());
    }


    private void doSomeThing(Object task) {
        log.info("业务计算 task:{}",task);
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        ThreadHistory2 history1 = new ThreadHistory2();
        new Thread(history1).start();


        new Thread(() -> {
            while (true){
                history1.deque.add(RandomUtil.randomChinese());
            }
        }).start();

        try {
            // 5秒后，停止执行
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info("停止业务计算");
        if (history1.running.compareAndSet(true, false)) {
            log.info("设置了标志位");
        }

    }
}
